package com.anbinh.doctor.fragment.benhnhan;

import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;

import com.anbinh.doctor.R;
import com.anbinh.doctor.adapter.PatientsAdapter;
import com.anbinh.doctor.model.DataResponse;
import com.anbinh.doctor.model.Notification;
import com.anbinh.doctor.model.ResponsePatient;
import com.anbinh.doctor.model.ResponsePatient.Patient;
import com.anbinh.doctor.model.UserLogin;
import com.anbinh.doctor.request.controller.ServerController;
import com.anbinh.doctor.service.request.OnRequest;
import com.anbinh.doctor.utils.IRcallBak;
import com.anbinh.doctor.utils.Utils;
import com.lsjwzh.widget.materialloadingprogressbar.CircleProgressBar;

public class FragmentListPatients extends Fragment implements OnScrollListener {
	public static FragmentListPatients fragment = null;
	private View mView;
	private CircleProgressBar mLoading;
	private ListView mListview;
	private UserLogin userLogin;

	private List<Patient> mList = null;
	private PatientsAdapter adapter;
	protected Patient currentPatient;
	private int currentPage = 0;
	private int mCurrentDoctorId = -1;
	private boolean isLoadding = false;
	public boolean isRefreshPatient = false;
	protected boolean isLongclick;
	protected int currentLocation;
	private IRcallBak callIResult;

	public static FragmentListPatients newInstance() {
		if (fragment == null) {
			fragment = new FragmentListPatients();
		}
		return fragment;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		if (activity instanceof IRcallBak) {
			callIResult = (IRcallBak) activity;
		}
	}

	public void onResetData() {
		currentPage = 0;
		adapter = null;
	}

	public void setRefreshPatient(boolean isRefreshPatient) {
		this.isRefreshPatient = isRefreshPatient;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mView = inflater.inflate(R.layout.fragment_message, null);
		onResetData();
		return mView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		mListview = (ListView) mView.findViewById(R.id.listView1);

		mListview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				if (isLongclick)
					return;

				currentPatient = mList.get(position);
				Bundle bundle = new Bundle();
				bundle.putInt(Utils.KEY, Utils.PATIENT_DETAILT);
				bundle.putBoolean(Utils.CUSTOMBAR, false);
				bundle.putBoolean(Utils.KEY_IS_SEARCH, false);

				bundle.putString(Utils.TITLE,
						getResources().getString(R.string.chi_tiet_benh_nhan));
				Utils.getNewIntent(getActivity(), bundle);
			}

		});
		mListview.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				isLongclick = true;
				currentLocation = position;
				callIResult.onDisplay(Utils.DELETE_PATIENTS, null);
				return false;
			}

		});

		mLoading = (CircleProgressBar) mView.findViewById(R.id.loadding);
		onLoadData();
		mListview.setOnScrollListener(this);

	}

	public Patient getCurrentPatient() {
		return currentPatient;
	}

	public void onLoadData() {
		isLoadding = true;
		currentPage++;
		userLogin = Utils.getAccountModel(getActivity(), Utils.KEY_USER);
		Utils.onLoadding(mView, true);

		ServerController.getInstance(getActivity()).requestListPatients(
				userLogin.getData().getToken(), currentPage, mCurrentDoctorId,
				"", new OnRequest<ResponsePatient>() {
					@Override
					public void onSuccess(ResponsePatient data) {
						if (getActivity() == null)
							return;
						isLoadding = false;
						Utils.onLoadding(mView, false);
						if (data.getResponsecode() >= 0
								&& data.getData() != null
								&& data.getData().getPatients().size() > 0) {

							currentPage = data.getData().getPaging()
									.getCurrentPage();
							int lastPage = data.getData().getPaging()
									.getLastPage();
							if (currentPage < lastPage) {
								isLoadding = false;
							} else {
								isLoadding = true;
							}
							if (adapter == null) {
								mList = data.getData().getPatients();
								if (mList == null || mList.size() == 0) {
									showViewNodata(R.drawable.ic_tab_bn_normal,
											R.string.chua_co_benh_nhan,
											R.string.vui_long_quay_lai_sau);
									return;
								}

								adapter = new PatientsAdapter(getActivity(),
										R.layout.item_patients, mList);
								mListview.setAdapter(adapter);
							} else {
								mList.addAll(data.getData().getPatients());
								adapter.notifyDataSetChanged();
							}
						}

					}

					@Override
					public void onError(int errorCode, String message) {
						isLoadding = false;
						Utils.onLoadding(mView, false);
						showViewNodata(R.drawable.icon_error_wifi,
								R.string.error_network_title,
								R.string.error_network);
					}
				});
	}

	protected void showViewNodata(int icon, int title, int message) {
		mListview.setVisibility(View.GONE);
		View view = (View) mView.findViewById(R.id.view_none);
		view.setVisibility(View.VISIBLE);
		Utils.viewNodataLk(getActivity(), mView,
				Utils.getDesc(getActivity(), message),
				Utils.getDesc(getActivity(), title), icon, new IRcallBak() {

					@Override
					public void onDisplay(int type, Bundle data) {
						currentPage = 0;
						adapter = null;
						onLoadData();

					}
				});

	}

	public int getCurrentDoctorId() {
		return mCurrentDoctorId;
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		int lastInScreen = firstVisibleItem + visibleItemCount;
		if ((lastInScreen == totalItemCount)) {
			if (!isLoadding) {
				onLoadData();
			}
		}
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		// TODO Auto-generated method stub

	}

	public void onDelete() {

		if (currentLocation == -1)
			return;

		Utils.onLoadding(mView, true);
		UserLogin userLogin = Utils.getAccountModel(getActivity(),
				Utils.KEY_USER);
		if (userLogin == null)
			return;
		final Patient item = mList.get(currentLocation);

		ServerController.getInstance(getActivity()).requestDeletePatient(
				userLogin.getData().getToken(), -1, item.getId(),
				new OnRequest<DataResponse>() {

					@Override
					public void onSuccess(DataResponse data) {
						Utils.onLoadding(mView, false);
						if (getActivity() == null)
							return;
						if (data.getResponsecode() >= 0) {
							mList.remove(item);
							adapter.notifyDataSetChanged();
						}

					}

					@Override
					public void onError(int errorCode, String message) {
						Utils.onLoadding(mView, false);
					}
				});

	}

	public void setLongclick(boolean b) {
		isLongclick = b;

	}
}
